package com.song.tools.songtest.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.song.tools.core.exception.BusinessException;
import com.song.tools.core.exception.ExceptionCodeEnum;
import com.song.tools.core.util.ObjectUtils;
import com.song.tools.mvc.request.BatchIdRequest;
import com.song.tools.mvc.request.PageRequest;
import com.song.tools.mvc.response.DeleteResponse;
import com.song.tools.mvc.response.PageResponse;
import com.song.tools.mvc.validator.ValidationException;
import com.song.tools.mvc.validator.ValidationResult;
import com.song.tools.songtest.beans.bo.DictionaryBo;
import com.song.tools.songtest.beans.poi.DictionaryExportDto;
import com.song.tools.songtest.beans.poi.DictionaryImportDto;
import com.song.tools.songtest.beans.query.DictionaryQuery;
import com.song.tools.songtest.beans.request.DictionaryQueryRequest;
import com.song.tools.songtest.beans.request.DictionarySaveRequest;
import com.song.tools.songtest.beans.request.DictionaryUpdateRequest;
import com.song.tools.songtest.beans.response.DictionaryDeleteResponse;
import com.song.tools.songtest.beans.response.DictionaryQueryResponse;
import com.song.tools.songtest.beans.response.DictionarySaveResponse;
import com.song.tools.songtest.beans.response.DictionaryUpdateResponse;
import com.song.tools.songtest.config.DistributedSnowflake;
import com.song.tools.songtest.convertor.DictionaryConvertor;
import com.song.tools.songtest.dao.entity.Dictionary;
import com.song.tools.songtest.manager.DictionaryManager;
import com.song.tools.songtest.service.DictionaryService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author song tools
 * @since 2024-07-12
 */
@Slf4j
@Service
public class DictionaryServiceImpl implements DictionaryService {

    @Resource
    private DictionaryManager dictionaryManager;

    @Resource
    private DictionaryConvertor dictionaryConvertor;

    @Resource
    private DistributedSnowflake distributedSnowflake;

    private static final Map<String, SFunction<Dictionary, ?>> COLUMNS_FUNCTION_MAP;
    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", Dictionary::getId,
                "dictionaryId", Dictionary::getDictionaryId
        );
    }


    /**
     * 通过主键列表批量删除
     *
     * @param request 主键列表请求体
     * @return 删除结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DictionaryDeleteResponse deleteByPrimaryKeys(BatchIdRequest<Long> request) {
        List<Long> primaryKeys = request.getIds();
        if (CollUtil.isEmpty(primaryKeys)) {
            throw new BusinessException(ExceptionCodeEnum.PARAM_NOT_NULL);
        }

        // 如果列表很大，考虑分批删除以减轻数据库压力
        int batchSize = 100; // 每批处理100条
        int totalDeleted = 0; // 记录总共删除的行数

        for (int i = 0; i < primaryKeys.size(); i += batchSize) {
            int toIndex = Math.min(i + batchSize, primaryKeys.size());
            List<Long> batchKeys = primaryKeys.subList(i, toIndex);

            int rows = dictionaryManager.deleteBatchByPrimaryKeys(batchKeys);
            totalDeleted += rows;
        }

        DictionaryDeleteResponse response = new DictionaryDeleteResponse();
        response.setDeleted(totalDeleted > 0 ? DeleteResponse.DELETED_SUCCESS : DeleteResponse.DELETED_FAIL);
        return response;
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public DictionaryQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        DictionaryBo dictionaryBo = dictionaryManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, Dictionary::getId));
        return dictionaryConvertor.entityBoToQueryResponse(dictionaryBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<DictionaryQueryResponse> list(DictionaryQueryRequest request) {
        DictionaryQuery dictionaryQuery = dictionaryConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(dictionaryQuery)) {
            List<DictionaryBo> dictionaryList = dictionaryManager.list(dictionaryQuery);
            if (ObjectUtils.isNotEmpty(dictionaryList)) {
                return dictionaryList.stream()
                        .map(dictionaryConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<DictionaryQueryResponse> listPages(PageRequest<DictionaryQueryRequest> request) {
        try {
            // 分页查询
            IPage<DictionaryBo> dictionaryPage = dictionaryManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(dictionaryPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param dictionaryPage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<DictionaryQueryResponse> safelyConvertPage(IPage<DictionaryBo> dictionaryPage) {
        if (dictionaryPage == null || dictionaryPage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<DictionaryQueryResponse> responses = dictionaryPage.getRecords().parallelStream()
            .map(dictionaryBo -> dictionaryConvertor.entityBoToQueryResponse(dictionaryBo))
            .collect(Collectors.toList());

        return PageResponse.convertPage(dictionaryPage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<DictionaryQuery> transformToQuery(PageRequest<DictionaryQueryRequest> request) {
        DictionaryQuery dictionaryQuery = dictionaryConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), dictionaryQuery);
    }


    /**
     * 新增
     *
     * @param saveRequest 请求入参
     * @return 响应
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DictionarySaveResponse save(DictionarySaveRequest saveRequest) {
        // 校验请求入参
        ValidationResult validationResult = validateOnSave(saveRequest);
        if (!validationResult.isValid()) {
            throw ValidationException.message(validationResult.getErrorMessage());
        }

        // 设置字典ID
        if (ObjectUtils.isEmpty(saveRequest.getDictionaryId())) {
            saveRequest.setDictionaryId(distributedSnowflake.nextIdStr());
        }

        // 根据入参封装 BO对象
        DictionaryBo dictionaryBo = dictionaryConvertor.saveRequestToEntityBo(saveRequest);

        // 数据库操作：插入数据
        int rows = dictionaryManager.save(dictionaryBo);

        // 处理插入结果
        boolean saveSuccess = rows > 0;
        // 新增数据成功，返回结果
        if (saveSuccess) {
            // 修改后的数据通过数据库查询返回
            DictionaryBo savedDictionaryBo = dictionaryManager.getOneByUniqueKey(dictionaryBo.getId(), Dictionary::getId);
            return dictionaryConvertor.entityBoToSaveResponse(savedDictionaryBo);
        }

        // 新增数据失败，抛出异常
        throw new BusinessException(ExceptionCodeEnum.CREATE_ERROR);
    }

    /**
    * 修改
    *
    * @param updateRequest 请求
    * @return 响应
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DictionaryUpdateResponse update(DictionaryUpdateRequest updateRequest) {
        // 校验请求入参
        ValidationResult validationResult = validateOnUpdate(updateRequest);
        if (!validationResult.isValid()) {
            throw ValidationException.message(validationResult.getErrorMessage());
        }

        // 根据入参封装 BO对象
        DictionaryBo dictionaryBo = dictionaryConvertor.updateRequestToEntityBo(updateRequest);

        // 数据库操作：修改数据
        int rows = dictionaryManager.updateByPrimaryKey(dictionaryBo);

        // 处理修改结果
        boolean updateSuccess = rows > 0;
        // 修改数据成功，返回结果
        if (updateSuccess) {
            // 修改后的数据通过数据库查询返回
            DictionaryBo updatedDictionaryBo = dictionaryManager.getOneByUniqueKey(dictionaryBo.getId(), Dictionary::getId);
            return dictionaryConvertor.entityBoToUpdateResponse(updatedDictionaryBo);
        }

        // 修改数据失败，抛出异常
        throw new BusinessException(ExceptionCodeEnum.UPDATE_ERROR);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file) {
        try {
            // 默认每次会读取100条数据
            EasyExcel.read(file.getInputStream(), DictionaryImportDto.class, new PageReadListener<DictionaryImportDto>(importDtos -> {
                ValidationResult validationResult = validateOnImport(importDtos);
                if (!validationResult.isValid()) {
                    throw ValidationException.message(validationResult.getErrorMessage());
                }

                // 数据转换
                List<DictionaryBo> dictionaryBos = dictionaryConvertor.importDtoToEntityBo(importDtos);
                // 保存到数据库
                dictionaryManager.saveBatch(dictionaryBos);
            })).sheet().doRead();
        } catch (Exception e) {
            log.warn("上传文件异常 {}", e.getLocalizedMessage(), e);
            throw new BusinessException(ExceptionCodeEnum.IMPORT_ERROR);
        }
    }


    @Override
    public void importTpl(HttpServletResponse response) {
        try {
            // 设置相应格式
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding("utf-8");

            // URLEncoder.encode 可以防止中文乱码
            String filename = "字典表_导入模版_" + LocalDateTime.now();
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + filename + ".xlsx");
            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), DictionaryImportDto.class).autoCloseStream(false).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
                excelWriter.write(Collections.emptyList(), writeSheet);
            }
        } catch (Exception e) {
            log.warn("导出模版异常 {}", e.getLocalizedMessage(), e);
            throw new RuntimeException(e);
        }
    }


    @Override
    public void export(HttpServletResponse response, DictionaryQueryRequest queryRequest) throws IOException {
        try {
            // 设置相应格式
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding("utf-8");

            // 分页请求
            PageRequest<DictionaryQueryRequest> pageRequest = new PageRequest<>();
            pageRequest.setData(queryRequest);
            pageRequest.setPageSize(500);
            pageRequest.setPageNum(1);

            PageRequest<DictionaryQuery> pageQuery = transformToQuery(pageRequest);

            // URLEncoder.encode 可以防止中文乱码
            String filename = "字典表_" + LocalDateTime.now();
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + filename + ".xlsx");
            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), DictionaryExportDto.class).autoCloseStream(false).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();

                long totalPage = 0;
                while (true) {
                    // 从数据库中读取数据
                    IPage<DictionaryBo> dictionaryPage = dictionaryManager.page(pageQuery);
                    if (dictionaryPage.getTotal() > 100_000) {
                        throw new BusinessException(ExceptionCodeEnum.EXPORT_TOO_MUCH);
                    }
                    if (dictionaryPage.getPages() != 0) {
                        totalPage = dictionaryPage.getPages();
                    }

                    // 查到的结果为空
                    if (dictionaryPage.getRecords().isEmpty()) {
                        break;
                    }

                    // 写入到 excel 中
                    List<DictionaryExportDto> exportVos = dictionaryPage.getRecords().stream().map(dictionaryConvertor::entityBoToExportDto).collect(Collectors.toList());
                    excelWriter.write(exportVos, writeSheet);

                    // 没有下一页，跳出循环
                    if (dictionaryPage.getCurrent() >= totalPage) {
                        break;
                    }

                    // 请求下一页
                    pageRequest.setPageNum(pageRequest.getPageNum() + 1);
                }
            }
        } catch (Exception e) {
            log.warn("导出文件异常 {}", e.getLocalizedMessage(), e);
            throw new BusinessException(ExceptionCodeEnum.EXPORT_ERROR);
        }
    }
}
